/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-04-04",
  "license": "MIT",
*/

const bodyParser = require('body-parser');
var jsonParser = bodyParser.json({ limit: '1000mb' });
const resbody = require('../utils/resbody');
const token = require('../utils/token');
const utils = require('../utils/utils');
const connection = require('../utils/sql');
const { log } = require('debug/src/node');
var mysql = require('mysql');
const escape = mysql.escape;

module.exports = (app) => {
	
	// 验证token
	const whiteList = ['/api/login'];

	app.use((req,res,next) => {
		if(!whiteList.includes(req.url)) {
			token.verifyToken(req.headers.authorization).then(res => {
				next()
			}).catch(e => {
				// token过期时的err值："message": "jwt expired",
				// token无效时的err值："message": "jwt malformed | invalid token | invalid signature",
				// 没有token的err值："message": "jwt must be provided"
				let msg = token.tokenMsg().find(item => item.type === e.message)['msg']
				// res.status(200).send(res.json(resbody.getFailResult({}, msg)))
				res.json(resbody.getFailResult({}, msg))
			})
		} else {
			next()
		}
	})
	
	// 登录
	app.post('/api/login', (req, res) => {
		
	    // 1. 接收普通键值对的参数
	    const { name, password } = req.body
	    const id = utils.randomNumber();
	    // 判断验证
	    if (!name) {
	        res.json({msg:'用户名不能为空', code: 0})
	        return false
	    }
	    if (!password) {
	        res.json({msg:'密码不能为空', code: 0})
	        return false
	    }
	    // 2. 添加到登录日志中并返回token
	    let posts = {
	        id: id,
	        loginName: name,
	        loginTime: new Date(),
			ipAddress: req.ip.match(/\d+\.\d+\.\d+\.\d+/),
			browser: req.header('sec-ch-ua') ? req.header('sec-ch-ua').split(',')[1] : '',
			os: req.header('sec-ch-ua-platform') ? req.header('sec-ch-ua-platform') : '',
			isDelete: '1'
	    }
		
		// 查询数组
		const userSql = `SELECT * FROM user`;

		connection(userSql, (error, result, fileds) => {
			if(error) {
				res.json(resbody.getFailResult(error))
			}else{
				let userData = result.find(item => escape(item.loginName) === escape(name));

				if (userData === undefined) {
					res.json(resbody.getFailResult({}, '该用户不存在', 0))
					return false
				}
				let userPassword = result.find(item => escape(item.password) === escape(password));
				if (userPassword === undefined || userPassword.loginName !== name) {
					res.json(resbody.getFailResult({}, '密码输入错误', 0))
					return false
				}
				const loginInfoSql = 'INSERT INTO loginInfo SET?';
				posts.name = result.find(item => escape(item.loginName) === escape(name))['name'];
				connection(loginInfoSql, posts, (error, result, fileds) => {
					if(error) {
						console.log(error)
						res.json(resbody.getFailResult(error))
					} else {
						let tokenData = {
							id: userData.id,
							name: userData.name,
							loginName: userData.loginName,
						}
						let getToken = token.createToken(tokenData);
						let data = {token: getToken}
						// 返回
						res.json(resbody.getSuccessResult(data, '登录成功'))
					}
				})
			}
		})
	})
}
